/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * 
 */

package controller;

import gui.View;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.swing.DefaultListModel;
import ni.ChatNI;
import protocol.*;

    

public class ChatController {

    private ChatNI ni;
    private DefaultListModel listUsers;
    private LocalUser localUser;
    private View view;
    private boolean connected;
    
    private File fileToSend;


    public ChatController() {
        this.listUsers = new DefaultListModel();
        connected = false;
    }

    public void setView(View v) {
        view = v;
    }

    public void launchNI()
    {
        ChatNI ni = new ChatNI(this);
        this.setNi(ni);

        this.controllerConnexion();

        connected = true;
    }

    public void createLocalUser (String s) {
        try {
            this.localUser = new LocalUser(s);
        } catch (UnknownHostException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void controllerDisplayMessage(ChatMessage cm){

        //Creation du contact associe au message
        User u = new User(cm.getUsername(),cm.getSourceAddress());
        Date d = new Date();

        int numTab = view.tabsContain(u);

        if(numTab == -1)
        {
            numTab = view.createTab(u);
        }

        view.viewDisplayText(numTab, u.getUserName()+" ("+DateFormat.getTimeInstance().format(d) +") dit: "+cm.getMessage()+"\n");
    }

    public void controllerConnexion() {
            ni.sendHelloBroadcast(true);
    }

    public void controllerDeconnexion() {
            ni.sendBye();
    }

    public void controllerDisplayHello(Hello h){
        //TODO : recherche du numéro d'onglet à partir du nom et de l'adresse IP
        Date d = new Date();
        String s = "#" + h.getUsername() +" ("+DateFormat.getTimeInstance().format(d) +") "+ " vient de se connecter.\n";

        //0 est le numéro de la fenetre principale
        view.viewDisplayText(0, s);
    }
    
    public void controllerDisplayBye(Bye b){
        Date d = new Date();
        String s = "#" + b.getUsername() +" ("+DateFormat.getTimeInstance().format(d) +") "+ " vient de se deconnecter.\n";

        //0 est le numéro de la fenetre principale
        view.viewDisplayText(0, s);
        
    }

    public void controllerDisplayAckFile(AckFile af)
    {
        User u = new User(af.getUsername(), af.getSourceAddress());
        Date d = new Date();
        String s = "#" + af.getUsername() +" ("+DateFormat.getTimeInstance().format(d) +") ";

        if(af.isAck())
        {
            s += "a accepté votre envoi de fichier.\n";
            
            ni.sendFile(fileToSend, u.getUserAddress(), this);

        }
        else {
            s += "a refusé votre envoi de fichier.\n";
        }

        int numTab = view.tabsContain(u);

        if(numTab == -1)
        {
            numTab = view.createTab(u);
        }
        //0 est le numéro de la fenetre principale
        view.viewDisplayText(numTab, s);
    }

    public void controllerDisplayFileArrived(String filename)
    {
        view.viewDisplayFileArrived(filename);
    }

    public void controllerSendHelloBack(boolean b, User u) {
        ni.sendHelloBack(b, u);
    }

    public void controllerSendBye()
    {
        if(connected)
        {
            ni.sendBye();
        }
    }

    public void controllerSendByeAndCloseThread()
    {
        ni.getUdps().setActive(false);

        ni.sendBye();

        connected = false;
    }

    public void controllerSendChatMessage(User u, String s)
    {
        ni.sendChatMessage(u, s);
    }

    public void controllerSendFileNotify(User u, File f)
    {
        ni.sendFileNotify(u, f);
        
        fileToSend = f;
    }

    public void controllerSendAckFile(User u, boolean ack, String filename, long taille)
    {
        if(ack)
        {    
            ni.receiveFile(filename, taille, this);
        }
        
        ni.sendAckFile(u, ack);
    }

    public void controllerDisplayFileNotify(FileNotify fn)
    {
        User u = new User(fn.getUsername(), fn.getSourceAddress());
        Date d = new Date();
        String s = "#" + fn.getUsername() +" ("+DateFormat.getTimeInstance().format(d) +") "+ " vous propose un fichier.\n";


        int numTab = view.tabsContain(u);

        if(numTab == -1)
        {
            numTab = view.createTab(u);
        }
        //0 est le numéro de la fenetre principale
        view.viewDisplayText(numTab, s);
        view.viewOpenFileDialog(fn.getNomFichier(), fn.getTaille());
    }

    public void controllerAddUser(String s, InetAddress ad)
    {
        boolean isContained = false;
        int i = 0;

        while(!isContained && i < listUsers.getSize())
        {
             User u = (User)listUsers.getElementAt(i);
 
            if(u.getUserAddress().equals(ad))
            {
                isContained = true;
                
                u.setUserName(s);

                listUsers.setElementAt(u, i);
            }

            i++;
        }

        if(!isContained)
        {
            listUsers.addElement(new User(s, ad));
        }
    }

    public void controllerRemoveUser(InetAddress ad)
    {
        int i = 0;
        boolean removed = false;
        
        while(!removed && i < listUsers.getSize())
        {
            User u = (User)listUsers.getElementAt(i);
 
            if(u.getUserAddress().equals(ad))
            {
                listUsers.removeElementAt(i);
                removed = true;
            }
            
            i++;
        }
    }

    public DefaultListModel getListUsers() {
        return listUsers;
    }

    public LocalUser getLocalUser() {
        return localUser;
    }

    /**
     * @param ni the ni to set
     */
    public void setNi(ChatNI ni) {
        this.ni = ni;
    }

}
